<%@page language="java" contentType="text/html; charset=UTF-8" isELIgnored="false" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="html" tagdir="/WEB-INF/tags" %>
<!DOCTYPE html>
<html>
<html:header title="经营状况日报">

    <link rel="stylesheet" href="${baseUrl}css/public.css" media="all">
    <script src="${baseUrl}js/myEchart.js" charset="utf-8"></script>

    <style type="text/css">
        .layui-card {border:1px solid #f2f2f2;border-radius:5px;}
        .panel {background-color:#fff;border:1px solid transparent;border-radius:3px;-webkit-box-shadow:0 1px 1px rgba(0,0,0,.05);box-shadow:0 1px 1px rgba(0,0,0,.05)}
        .panel-body {padding:10px}
        .panel-title {margin-top:0;margin-bottom:0;font-size:12px;color:inherit}
        .layui-bg-number {background-color:#F8F8F8;}
    </style>

    <script>
        jQuery(function () {
            fixTableOperatorButton();

            $("#table-button").click(function () {
                $(".view-button").removeClass("layui-btn-normal").addClass("layui-btn-primary").css("color","#1E9FFF");
                $(this).addClass("layui-btn-normal").css("color","#fff");

                $("#table-div").css("display","block");
                $("#chat-div").css("display","none");
            });
            $("#chat-button").click(function () {
                $(".view-button").removeClass("layui-btn-normal").addClass("layui-btn-primary").css("color","#1E9FFF");
                $(this).addClass("layui-btn-normal").css("color","#fff");

                $("#table-div").css("display","none");
                $("#chat-div").css("display","block");

                $("#stock-goods-bar-button").click();
                $("#stock-goods-pie-button").click();
            });

            $("#export").click(function () {
                exportExcel();
            });
        });


        layui.use(['form', 'table','laydate','laytpl','element'], function () {
            let $ = layui.jquery,
                form = layui.form,
                table = layui.table,
                laydate = layui.laydate,
                laytpl = layui.laytpl,
                element = layui.element,
                util = layui.util;

            laydate.render({
                elem: '#date',
                range:'~',
                <c:if test="${date1 != null and date2!= null}">
                value: "${date1} ~ ${date2}",
                </c:if>
                done: function(value, date, endDate){
                    if (!emptyEntity(value)) {
                        $('[name="date1"]').val(getDateFromLayUiDate(date));
                        $('[name="date2"]').val(getDateFromLayUiDate(endDate));
                    } else {
                        $('[name="date1"]').val('');
                        $('[name="date2"]').val('');
                    }

                    getAllTotalData();
                    loadView();
                }
            });

            $(".view-button-group .layui-btn").click(function () {
                tabButtonClick(this);
                loadView();
            });


            ajaxSelect("${baseUrl}organization/store/getStores.action","storeId","全部", function () {
                formSetVal("searchForm",{storeId:"${storeId}"});
                setTimeout(function () {
                    loadView();
                    getAllTotalData();
                },100);
            });


            table.on('tool(table)', function (obj) {
                let data = obj.data;
                if(obj.event == 'detail'){
                    openTab("员工销售明细","${baseUrl}financeCount/performanceAnalysisDetail.action"+genParam(genSearch()) + "&userId="+data.id);
                }
            });

            form.on('select(storeId)', function (data) {
                getAllTotalData();
                loadView();
            });

            form.on('checkbox(filterZero)', function (data) {
                table.reload('table',{where: genSearch(),page: {curr: 1}});
            });

            form.on('submit(search)', function (data) {
                table.reload('table',{where: genSearch(),page: {curr: 1}});
                return false;
            });
        });


        function exportExcel() {
            confirm("是否导出业绩报表?",function () {
                tipLoad("处理中，请稍后");
                post("${baseUrl}financeCount/performanceAnalysis/export.action"+ genParam(genSearch()),{},function (res) {
                    closeAll();
                    if (res.code == 1) {
                        downloadFileByForm("${baseUrl}file/excel/temp/"+res.data);
                    }  else {
                        tip(res.msg);
                    }
                });
            });
        }

        function genSearch() {
            let json = getFormJson($("#searchForm"));
            json.filterZero = $('[name="filterZero"]').next().hasClass("layui-form-checked") ? true:'';
            return json;
        }

        function genChatSearch() {
            let json = getFormJson($("#searchForm"));
            json.filterZero = true;
            return json;
        }

        function renderTable() {
            layui.table.render({
                id:'table',
                elem: '#table',
                totalRow:true,
                url: "${baseUrl}financeCount/performanceAnalysis/listUserData.action",
                where : genSearch(),
                cols: [[
                    {width:70,title:"序号",templet:function (d) {
                            return d.LAY_INDEX;;
                        }},
                    {field: 'name',width: 150, title: '姓名',style:"font-size:12px;"},
                    {field: 'username', width: 150, title: '登录账号',style:"font-size:12px;"},

                    {field: 'number',width: 120, title: '销售笔数',style:"font-size:12px;"},
                    {field: 'amount',width: 120, title: '销售额',style:"font-size:12px;",templet: function (d) {
                            return getPrice(d.amount);
                        }},
                    {field: 'ratio',width: 120, title: '销售比重',style:"font-size:12px;",templet: function (d) {
                            return getNumber(d.ratio) + '%';
                        }},
                    {field: 'avgAmount',width: 120, title: '销售均价',style:"font-size:12px;",templet: function (d) {
                            return getPrice(d.avgAmount);
                        }},
                    {field: 'profits',width: 120, title: '销售毛利',style:"font-size:12px;",templet: function (d) {
                            return getPrice(d.profits);
                        }},
                    {field: 'tax',width: 120, title: '销售税额',style:"font-size:12px;",templet: function (d) {
                            return getPrice(d.tax);
                        }},
                    {field: 'refundNum',width: 120, title: '销售退货笔数',style:"font-size:12px;",templet: function (d) {
                            return getNumber(d.refundNum);
                        }},
                    {field: 'refundAmt',width: 120, title: '销售退货额',style:"font-size:12px;",templet: function (d) {
                            return getPrice(d.refundAmt);
                        }},
                    {title: '操作', minWidth: 80,fixed:'right', templet: '#operBar'},
                ]],
                limit: 10,
                page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                    layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                    //,curr: 5 //设定初始在第 5 页
                    ,groups: 5 //只显示 5 个连续页码
                    ,first: false //不显示首页
                    ,last: false //不显示尾页
                },
                done: function(res, curr, count){
                    let number = 0;
                    let amount = 0;
                    let profits = 0;
                    let tax = 0;
                    let refundNum = 0;
                    let refundAmt = 0;
                    $.each(res.data, function (i,d) {
                        number += parseFloat(d.number);
                        amount += parseFloat(d.amount);
                        profits += parseFloat(d.profits);
                        tax += parseFloat(d.tax);
                        refundNum += parseFloat(d.refundNum);
                        refundAmt += parseFloat(d.refundAmt);
                    });
                    setTotalRowWithParent($('[lay-id="table"]'),"number",getNumber(number));
                    setTotalRowWithParent($('[lay-id="table"]'),"amount",getPrice(amount));
                    setTotalRowWithParent($('[lay-id="table"]'),"profits",getPrice(profits));
                    setTotalRowWithParent($('[lay-id="table"]'),"tax",getPrice(tax));
                    setTotalRowWithParent($('[lay-id="table"]'),"refundNum",getNumber(refundNum));
                    setTotalRowWithParent($('[lay-id="table"]'),"refundAmt",getPrice(refundAmt));
                    setTotalRowWithParent($('[lay-id="table"]'),"0","合计");
                }
            });
        }

        function getAllTotalData() {
            get("${baseUrl}financeCount/performanceAnalysis/getAllTotalData.action"+genParam(genSearch()), function (res) {
                if (res.code == 1 && !emptyList(res.data)) {
                    $("#saleNumber").html(res.data.total_sale_number);
                    $("#saleAmount").html(getPrice(res.data.total_sale_amt));
                    $("#saleProfits").html(getPrice(res.data.total_sale_profits));
                    let rate = res.data.total_sale_profits*100/res.data.total_sale_amt;
                    $("#profitsRate").html(getNumber(rate));

                    if (emptyEntity(res.data.highSaleUser)) {
                        $("#highUser").html("无");
                        $("#highUserAmount").html(getPrice(0));
                    } else {
                        $("#highUser").html(res.data.highSaleUser.name);
                        $("#highUserAmount").html(getPrice(res.data.highSaleUser.amount));
                    }
                }
            });
        }


        function loadView(){
            var viewId = $(".view-button-group .layui-this").attr("view-id");
            if (viewId.indexOf("table") != -1) {
                renderTable();
            } else {
                loadChartView();
            }
        }
    </script>

</html:header>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">
        <form class="layui-form" action="" id="searchForm" lay-filter="searchForm">
            <input type="hidden" name="date1" value="${date1}">
            <input type="hidden" name="date2" value="${date2}">

            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">门店</label>
                    <div class="layui-input-inline">
                        <select name="storeId" lay-filter="storeId" value="${storeId}"></select>
                    </div>
                </div>

                <div class="layui-inline">
                    <label class="layui-form-label">日期范围</label>
                    <div class="layui-input-inline">
                        <input type="text" id="date" placeholder="请选择日期" class="layui-input" autocomplete="off">
                    </div>
                </div>

                <div class="layui-inline">
                    <div class="layui-input-inline">
                        <div class="layui-btn-group view-button-group">
                            <a view-id="table-div" view-class="view-div" class="layui-btn layui-btn-normal fontWhite layui-this">列表视图</a>
                            <a view-id="chat-div" view-class="view-div" class="layui-btn layui-btn-primary fontBlue">图表视图</a>
                        </div>
                    </div>
                </div>
            </div>


            <div class="layui-card">
                <div class="layui-card-body">
                    <div class="w100">
                        <div class="layui-row layui-col-space10">
                            <div class="layui-col-xs6 layui-col-sm3 layui-col-md3">
                                <div class="panel layui-bg-number">
                                    <div class="panel-body">
                                        <div class="panel-title">
                                            <h5>销售笔数</h5>
                                        </div>
                                        <div class="panel-content">
                                            <span class="fontB fontRed font24" id="saleNumber">1234</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="layui-col-xs6 layui-col-sm3 layui-col-md3">
                                <div class="panel layui-bg-number">
                                    <div class="panel-body">
                                        <div class="panel-title">
                                            <h5>销售额</h5>
                                        </div>
                                        <div class="panel-content">
                                            <span class="fontB fontRed font24" id="saleAmount"></span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="layui-col-xs6 layui-col-sm3 layui-col-md3">
                                <div class="panel layui-bg-number">
                                    <div class="panel-body">
                                        <div class="panel-title">
                                            <h5>销售毛利</h5>
                                        </div>
                                        <div class="panel-content">
                                            <span class="fontB fontRed font24" id="saleProfits"></span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="layui-col-xs6 layui-col-sm3 layui-col-md3">
                                <div class="panel layui-bg-number">
                                    <div class="panel-body">
                                        <div class="panel-title">
                                            <h5>毛利率</h5>
                                        </div>
                                        <div class="panel-content">
                                            <span class=" fontB fontRed font24" id="profitsRate"></span>
                                            <span class="fontRed font14">%</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="layui-col-xs12 layui-col-sm6 layui-col-md6">
                                <div class="panel layui-bg-number">
                                    <div class="panel-body">
                                        <div class="panel-title">
                                            <h5>销售冠军</h5>
                                        </div>
                                        <div class="panel-content">
                                            <span class=" fontB fontDeepBlue font14" id="highUser">无</span>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="layui-col-xs12 layui-col-sm6 layui-col-md6">
                                <div class="panel layui-bg-number">
                                    <div class="panel-body">
                                        <div class="panel-title">
                                            <h5>冠军销售额</h5>
                                        </div>
                                        <div class="panel-content">
                                            <span class=" fontB fontDeepBlue font14" id="highUserAmount">无</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>



            <div id="chat-div" class="view-div mt10" style="display: none">
                <div>
                    <div class="layui-card">
                        <div class="layui-card-header">
                            <div class="layui-inline">
                                <input type="radio" name="chat-rank-flag" value="1" title="销售排行" lay-filter="chat-rank-flag" checked>
                                <input type="radio" name="chat-rank-flag" value="2" title="毛利排行" lay-filter="chat-rank-flag">
                            </div>
                        </div>
                        <div class="layui-card-body">
                            <div id="chat-rank" class="h300"></div>

                            <div class="h300 lh300 font20 fontB fontC_ccc" style="text-align: center;display: none;">
                                统计值为0或负数无法统计
                            </div>
                        </div>
                    </div>
                </div>

                <div>
                    <div class="layui-card">
                        <div class="layui-card-header">
                            <div class="layui-inline">
                                <input type="radio" name="chat-ratio-flag" value="1" title="销售比重" lay-filter="chat-ratio-flag" checked>
                                <input type="radio" name="chat-ratio-flag" value="2" title="毛利比重" lay-filter="chat-ratio-flag">
                            </div>
                        </div>
                        <div class="layui-card-body">
                            <div id="chat-ratio" class="h300"></div>

                            <div class="h300 lh300 font20 fontB fontC_ccc" style="text-align: center;display: none;">
                                统计值为0或负数无法统计
                            </div>
                        </div>
                    </div>
                </div>

                <div>
                    <div class="layui-card">
                        <div class="layui-card-header">

                            销售趋势
                            <div class="layui-inline fr">
                                <div class="label" style="min-width: 20px;">经手人</div>
                                <div style="display: inline-block;width: 160px;">
                                    <select name="trend-userId" lay-filter="trend-userId">
                                    </select>
                                </div>
                            </div>

                            <div style="clear: both;"></div>
                        </div>
                        <div class="layui-card-body">
                            <div id="sale-trend" class="h300"></div>
                        </div>
                    </div>
                </div>

                <script>
                    function loadChartView(){

                        layui.use(['form', 'echarts'], function () {
                            let $ = layui.jquery,
                                form = layui.form,
                                echarts = layui.echarts;
                            window.chat_rank_chat = echarts.init(document.getElementById('chat-rank'),'walden');
                            window.chat_ratio_chat = echarts.init(document.getElementById('chat-ratio'),'walden');
                            window.sale_trend_chat = echarts.init(document.getElementById('sale-trend'),'walden');

                            window.onresize = function(){
                                window.chat_ratio_chat.resize();
                                window.chat_rank_chat.resize();
                                window.sale_trend_chat.resize();
                            };

                            form.on('select(trend-userId)', function (data) {
                                genUserData(data.value);
                            });

                            form.on('radio(chat-rank-flag)', function (data) {
                                let chartData;
                                if (data.value == '1') {
                                    chartData = JSON.parse($("#chat-rank").attr("saleData"));
                                } else {
                                    chartData = JSON.parse($("#chat-rank").attr("profitsData"));
                                }
                                window.chat_rank_chat.setOption(genChatRankOption(chartData));
                            });
                            form.on('radio(chat-ratio-flag)', function (data) {
                                let chartData;
                                if (data.value == '1') {
                                    chartData = JSON.parse($("#chat-ratio").attr("saleData"));
                                } else {
                                    chartData = JSON.parse($("#chat-ratio").attr("profitsData"));
                                }
                                window.chat_ratio_chat.setOption(genChatRatioOption(chartData));
                            });

                            let url = "${baseUrl}financeCount/performanceAnalysis/listUserData.action"+genParam(genChatSearch());
                            get(url, function (res) {
                                if (!emptyList(res.data)) {
                                    $("#chat-rank").css("display","block");
                                    $("#chat-rank").next().css("display","none");
                                    $("#chat-ratio").css("display","block");
                                    $("#chat-ratio").next().css("display","none");
                                    $("#chat-rank").attr("saleData",JSON.stringify(genChatRankData("销售额","amount",res.data)));
                                    $("#chat-ratio").attr("saleData",JSON.stringify(genChatRatioData("销售额","amount",res.data)));

                                    let profitsList = res.data.sort(function(a,b){
                                        return b.profits-a.profits ;
                                    });

                                    $("#chat-rank").attr("profitsData",JSON.stringify(genChatRankData("毛利","profits",profitsList)));
                                    $("#chat-ratio").attr("profitsData",JSON.stringify(genChatRatioData("毛利","profits",profitsList)));

                                    let chartData;
                                    if (getFormJson($("#searchForm"))["chat-rank-flag"] == '1') {
                                        chartData = JSON.parse($("#chat-rank").attr("saleData"));
                                    } else {
                                        chartData = JSON.parse($("#chat-rank").attr("profitsData"));
                                    }
                                    window.chat_rank_chat.setOption(genChatRankOption(chartData));

                                    if (getFormJson($("#searchForm"))["chat-ratio-flag"] == '1') {
                                        chartData = JSON.parse($("#chat-ratio").attr("saleData"));
                                    } else {
                                        chartData = JSON.parse($("#chat-ratio").attr("profitsData"));
                                    }
                                    window.chat_ratio_chat.setOption(genChatRatioOption(chartData));
                                } else {
                                    $("#chat-rank").css("display","none");
                                    $("#chat-rank").next().css("display","block");
                                    $("#chat-ratio").css("display","none");
                                    $("#chat-ratio").next().css("display","block");
                                }
                            });
                            loadTrendView();



                            function loadTrendView() {
                                let ajax1= get("${baseUrl}goodsCount/saleAnalysis/chatDetailData.action"+genParam(genSearch()), function (res) {
                                    if (!emptyList(res.data)) {
                                        let data={};
                                        data.xData = [];
                                        data.total = [];
                                        for (let key in res.data) {
                                            data.xData.push(key);
                                            data.total.push(getPrice(res.data[key]));
                                        }
                                        $("#sale-trend").attr("data", JSON.stringify(data));
                                    }


                                });

                                $.when(ajax1).done(function () {
                                    ajaxSelect("${baseUrl}user/user/getAll.action.action","trend-userId",null, function (data) {
                                        let userMap={};
                                        $.each(data, function (i,d) {
                                            userMap[d.id] = d.name;
                                        });

                                        $("#sale-trend").attr("userMap", JSON.stringify(userMap));

                                        if (!emptyList(data)) {
                                            genUserData(data[0].id);
                                        }
                                    });
                                });
                            }

                            function genUserData(userId) {
                                var userMap = JSON.parse($("#sale-trend").attr("userMap"));
                                var data = JSON.parse($("#sale-trend").attr("data"));

                                get("${baseUrl}goodsCount/saleAnalysis/chatDetailData.action"+genParam(genSearch())+"&userId="+userId, function (res) {
                                    if (res.data !=null) {
                                        let userData = [];
                                        for (let key in res.data) {
                                            userData.push(getPrice(res.data[key]));
                                        }


                                        window.sale_trend_chat.setOption(genChatLineOption(userMap[userId], data.xData, data.total,userData));
                                    }
                                });
                            }

                            function genChatLineOption(user, xData, total, userData) {
                                let option = {
                                    title: {
                                        text: '销售趋势'
                                    },
                                    tooltip: {
                                        trigger: 'axis'
                                    },
                                    legend: {
                                        orient: 'horizontal', // 'vertical'
                                        x: 'center', // 'center' | 'left' | {number},
                                        y: 'bottom', // 'center' | 'bottom' | {number}
                                        data: ['合计销售额', user+'的销售额']
                                    },
                                    grid: {
                                        left: '3%',
                                        right: '4%',
                                        bottom: '10%',
                                        containLabel: true
                                    },
                                    xAxis: {
                                        type: 'category',
                                        // boundaryGap: false,
                                        data: xData
                                    },
                                    yAxis: {
                                        type: 'value'
                                    },
                                    series: [
                                        {
                                            name: '合计销售额',
                                            type: 'line',
                                            stack: '',
                                            data: total
                                        },
                                        {
                                            name: user+'的销售额',
                                            type: 'line',
                                            stack: '',
                                            data: userData
                                        },
                                    ]
                                };

                                return option;
                            }
                        });
                    }
                </script>
            </div>

            <div id="table-div" class="view-div mt10">
                <div class="layui-inline mb4">
                    <div class="label">过滤零销售</div>
                    <div style="display: inline-block;width: 30px;">
                        <input type="checkbox" name="filterZero"  title="" lay-skin="primary" value="true" checked lay-filter="filterZero">
                    </div>
                </div>

                <div class="layui-inline mb4">
                    <div class="label">搜索信息</div>
                    <div style="display: inline-block;width: 160px;">
                        <input type="text" name="search" placeholder="编号、名称、规格、属性" class="layui-input font12">
                    </div>
                </div>

                <div class="layui-inline mb4">
                    <div class="layui-btn-group">
                        <a class="layui-btn " lay-submit="" lay-filter="search" id="btn-search"><i class="layui-icon layui-icon-search"></i></a>
                        <a class="layui-btn layui-btn-primary" id="export">导出</a>
                    </div>
                </div>

                <table class="layui-hide" id="table" lay-filter="table" lay-size="sm"></table>
            </div>
        </form>
    </div>
</div>
</body>

<script type="text/html" id="operBar">
    <a class="layui-btn layui-btn-xs layui-btn-normal " lay-event="detail">详情</a>
</script>

<html:loading/>
</html>